/**
 * 
 */
package com.et114.components.ldap;

//import org.acegisecurity.providers.ldap.authenticator.PasswordComparisonAuthenticator;
import org.acegisecurity.userdetails.ldap.LdapUserDetails;
import org.acegisecurity.userdetails.ldap.LdapUserDetailsImpl;
import org.acegisecurity.userdetails.ldap.LdapUserDetailsMapper;
import org.acegisecurity.ldap.DefaultInitialDirContextFactory ;
import org.acegisecurity.providers.ldap.populator.DefaultLdapAuthoritiesPopulator;
import org.acegisecurity.ldap.LdapTemplate;
import org.acegisecurity.GrantedAuthority ;


/**
 * @author guanhw
 */
public class SpringLdapTestAcegi extends LdapTestCase {
//	private static PasswordComparisonAuthenticator passwordComparisonAuthenticator  ;
	DefaultLdapAuthoritiesPopulator defaultLdapAuthoritiesPopulator ;
	/**
	 * 
	 */
	public  void init(){
//		passwordComparisonAuthenticator = ( PasswordComparisonAuthenticator ) getBean( "passwordComparisonAuthenticator" ) ;
		defaultLdapAuthoritiesPopulator = ( DefaultLdapAuthoritiesPopulator ) getBean( "defaultLdapAuthoritiesPopulator" ) ;
	}
	

	
	public void test() {
		try {
			this.init();
			String username = "jbloggs" ; 
			DefaultInitialDirContextFactory didcf = ( DefaultInitialDirContextFactory ) getBean( "initialDirContextFactory" ) ;
			LdapTemplate lt = new LdapTemplate( didcf )  ;
			LdapUserDetailsMapper userDetailsMapper = new LdapUserDetailsMapper();
			Object obj = lt.retrieveEntry( "uid=jbloggs,ou=people,dc=mycompany,dc=com" , userDetailsMapper , null ) ;
			LdapUserDetailsImpl.Essence userEssence = ( LdapUserDetailsImpl.Essence ) obj ; 
			userEssence.setUsername( username ) ;
			LdapUserDetails user = userEssence.createUserDetails();
			
			//user = passwordComparisonAuthenticator.authenticate( username, "password" ) ;
			
			org.acegisecurity.GrantedAuthority[]  gas = defaultLdapAuthoritiesPopulator.getGrantedAuthorities( user ) ;
			for ( int i = 0 ; i < gas.length ; i ++ ) {
				GrantedAuthority ga = gas[ i ] ;
				logger.info( ">>>>" + ga.getAuthority() ) ;
			}
			
			logger.info( "..." + ( gas.length )  ) ;
		}
		catch ( Exception e ) {
			logger.error( e.getMessage() , e ) ; 
		}
	}
}
